<template>
  <div class="q-pa-md">
    <div class="q-gutter-md">
      <q-carousel
        v-model="slide"
        transition-next="slide-left"
        transition-prev="slide-right"
        swipeable
        animated
        control-color="black"
        navigation
        padding
        arrows
        height="400px"
        class="shadow-1"
      >
        <q-carousel-slide name="style" class="column flex-center">
          <q-img src="../assets/images/Post0.png" width="80%" fit="fit">
          </q-img>
        </q-carousel-slide>
        <q-carousel-slide name="tv" class="column no-wrap flex-center">
          <q-img
            src="../assets/images/Post1.png"
            :ratio="16 / 9"
            width="80%"
            fit="fit"
          >
          </q-img>
        </q-carousel-slide>
        <q-carousel-slide name="layers" class="column no-wrap flex-center">
          <q-img
            src="../assets/images/Post2.png"
            :ratio="16 / 9"
            width="80%"
            fit="fit"
          >
          </q-img>
        </q-carousel-slide>
      </q-carousel>
    </div>
  </div>

  <q-dialog v-model="dialog" seamless @click-outside="closeDialog">
    <q-card class="q-pa-md" style="width: 80vw; max-width: 600px">
      <!-- 帖子信息 -->
      <div class="text-h5 q-mb-md fontya">帖子记录</div>
      <div
        v-for="searchpost in searchposts"
        :key="searchpost.id"
        class="post-card"
      >
        <q-card-section class="text-blue bold">
          <div class="row items-start no-wrap">
            <div class="col">
              <p><strong>帖子日期:</strong> {{ searchpost.postdate }}</p>
              <p><strong>标题:</strong> {{ searchpost.title }}</p>
              <p><strong>内容:</strong> {{ searchpost.content }}</p>
            </div>
          </div>
        </q-card-section>
      </div>

      <!-- 回复信息 -->
      <div class="text-h5 q-mb-md fontya">回复记录</div>
      <div v-for="reply in replys" :key="reply.id" class="reply-card">
        <q-card-section class="text-blue bold">
          <div class="row items-start no-wrap">
            <div class="col">
              <p><strong>回复日期:</strong> {{ reply.replydate }}</p>
              <p><strong>回复内容:</strong> {{ reply.content }}</p>
              <p><strong>回复的帖子id:</strong> {{ reply.postid }}</p>
            </div>
          </div>
        </q-card-section>
      </div>

      <!-- 关闭按钮 -->
      <q-card-actions align="right">
        <q-btn v-close-popup label="Close" color="primary" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <div>
    <q-splitter v-model="splitterModel">
      <template #before>
        <q-tabs v-model="tab" vertical class="text-teal">
          <q-tab name="mails" icon="mail" label="帖子" />
          <q-tab name="post" icon="alarm" label="发帖" />
          <q-tab
            name="hot"
            icon="whatshot"
            label="热帖"
            @click="fetchHotPosts"
          />
        </q-tabs>
      </template>
      <template #after>
        <q-tab-panels
          v-model="tab"
          animated
          swipeable
          vertical
          transition-prev="jump-up"
          transition-next="jump-up"
        >
          <q-tab-panel name="mails">
            <div class="text-h3 q-mb-md fontya">交流中心</div>
            <div class="q-pa-md row items-start q-gutter-md">
              <q-card
                v-for="post1 in posts"
                :key="post1.id"
                class="my-card-post"
              >
                <q-card-section class="bg-primary text-white">
                  <div class="post-header row">
                    <img
                      :src="post1.imgUrl"
                      class="post-avatar"
                      alt=""
                      @error="imgError"
                      @click="openDialog(post1.userid)"
                    />
                    <div class="post-info">
                      <div id="username">{{ post1.username }}</div>
                      <div class="text-subtitle2">{{ post1.postdate }}</div>
                    </div>
                  </div>
                  <div class="container2 flex-center flex">
                    <div class="post-title">{{ post1.title }}</div>
                    <div class="post-content">{{ post1.content }}</div>
                  </div>
                  <!-- Like button and count -->
                  <div class="like-container">
                    <q-icon
                      :name="post1.isLike ? 'thumb_up' : 'thumb_up_off_alt'"
                      class="like-icon"
                      :style="{ color: post1.isLike ? 'blue' : 'grey' }"
                      @click="toggleLike(post1.id)"
                    />
                    <span>{{ post1.like }}</span>
                  </div>
                </q-card-section>
                <q-separator />
                <q-card-actions align="left" class="action-buttons">
                  <q-btn
                    flat
                    color="white"
                    class="bg-primary"
                    style="width: 10%"
                    @click="toggleReplyBox(post1.id)"
                  >
                    回复
                  </q-btn>
                  <q-btn
                    flat
                    color="white"
                    class="bg-negative"
                    style="width: 10%"
                    @click="deletePost(post1.id)"
                    >删帖
                  </q-btn>
                </q-card-actions>
                <q-card-section
                  v-if="replyBoxOpen[post1.id]"
                  class="colum items-start justify-evenly"
                >
                  <q-input v-model="text" filled label="回复" size="lg" />
                  <br />
                  <div class="col row" style="display: flex; gap: 10px">
                    <q-btn
                      flat
                      color="white"
                      icon="send"
                      class="bg-primary"
                      style="gap: 10px"
                      label="提交"
                      @click="submitReply(post1.id)"
                    />
                    <q-btn
                      flat
                      color="white"
                      icon="close"
                      class="bg-deep-orange"
                      label="取消"
                      @click="closeReplyBox(post1.id)"
                    />
                  </div>
                </q-card-section>
                <q-card-section>
                  <div class="replies">
                    <div
                      v-for="reply in post1.postReplyList"
                      :key="reply.id"
                      class="reply-card"
                    >
                      <q-item>
                        <q-item-section>
                          <div>{{ reply.content }}</div>
                          <div class="text-subtitle2">
                            {{ reply.replydate }}
                          </div>
                        </q-item-section>
                        <q-item-section avatar>
                          <q-avatar>
                            <img
                              :src="reply.imgUrl"
                              class="post-avatar"
                              alt=""
                              @error="imgError"
                              @click="openDialog(reply.userid)"
                            />
                          </q-avatar>
                          <div class="text-subtitle2">
                            By {{ reply.username }}
                          </div>
                        </q-item-section>
                      </q-item>
                    </div>
                  </div>
                </q-card-section>
              </q-card>
            </div>
            <div class="q-pa-lg flex flex-center">
              <q-pagination
                v-model="current"
                :max="totalPage"
                input
                @update:model-value="handlePageChange"
              />
            </div>
          </q-tab-panel>
          <q-tab-panel name="post">
            <div class="text-h3 q-mb-md">发帖</div>
            <div class="q-pa-md q-gutter-sm editor-container">
              <q-input v-model="postTitle" filled dense label="标题" />
              <q-input
                v-model="postContent"
                type="textarea"
                filled
                label="帖子内容"
              />
              <!-- <q-editor
                v-model="postContent"
                :dense="$q.screen.lt.md"
                :toolbar="toolbarOptions"
                :fonts="editorFonts"
              /> -->
              <q-btn
                class="q-mt-md"
                color="primary"
                label="发布"
                @click="submitNewPost"
              />
            </div>
          </q-tab-panel>
          <q-tab-panel name="hot">
            <div class="text-h3 q-mb-md fontya">热帖</div>
            <div class="q-pa-md row items-start q-gutter-md">
              <q-card
                v-for="hotPost in hotPosts"
                :key="hotPost.id"
                class="my-card-post"
              >
                <q-card-section class="bg-primary text-white">
                  <div class="post-header row">
                    <img
                      :src="hotPost.imgUrl"
                      class="post-avatar"
                      alt=""
                      @error="imgError"
                      @click="openDialog(hotPost.userid)"
                    />
                    <div class="post-info">
                      <div id="username">{{ hotPost.username }}</div>
                      <div class="text-subtitle2">{{ hotPost.postdate }}</div>
                    </div>
                  </div>
                  <div class="container2 flex-center flex">
                    <div class="post-title">{{ hotPost.title }}</div>
                    <div class="post-content">{{ hotPost.content }}</div>
                  </div>
                  <!-- Like button and count -->
                  <div class="like-container">
                    <q-icon
                      :name="hotPost.isLike ? 'thumb_up' : 'thumb_up_off_alt'"
                      class="like-icon"
                      :style="{ color: hotPost.isLike ? 'blue' : 'grey' }"
                      @click="toggleLike(hotPost.id)"
                    />
                    <span>{{ hotPost.like }}</span>
                  </div>
                </q-card-section>
                <q-separator />
                <!--                <q-card-actions align="left" class="action-buttons">-->
                <!--                  <q-btn flat color="primary" @click="toggleReplyBox(hotPost.id)">回复</q-btn>-->
                <!--                  <q-btn flat color="negative" @click="deletePost(hotPost.id)">删帖</q-btn>-->
                <!--                </q-card-actions>-->
                <!--                <q-card-section v-if="replyBoxOpen[hotPost.id]" class="reply-section">-->
                <!--                  <q-input v-model="text" filled label="回复" class="reply-input"/>-->
                <!--                  <div class="reply-buttons">-->
                <!--                    <q-btn color="primary" label="取消"  class="reply-button" @click="closeReplyBox(hotPost.id)"/>-->
                <!--                    <q-btn color="primary" label="提交"  class="reply-button" @click="submitReply(hotPost.id)"/>-->
                <!--                  </div>-->
                <!--                </q-card-section>-->
                <q-card-actions align="left" class="action-buttons">
                  <q-btn
                    flat
                    color="white"
                    class="bg-primary"
                    style="width: 10%"
                    @click="toggleReplyBox(hotPost.id)"
                  >
                    回复
                  </q-btn>
                  <q-btn
                    flat
                    color="white"
                    class="bg-negative"
                    style="width: 10%"
                    @click="deletePost(hotPost.id)"
                    >删帖
                  </q-btn>
                </q-card-actions>
                <q-card-section
                  v-if="replyBoxOpen[hotPost.id]"
                  class="colum items-start justify-evenly"
                >
                  <q-input v-model="text" filled label="回复" size="lg" />
                  <br />
                  <div class="col row" style="display: flex; gap: 10px">
                    <q-btn
                      flat
                      color="white"
                      icon="send"
                      class="bg-primary"
                      style="gap: 10px"
                      label="提交"
                      @click="submitReply(hotPost.id)"
                    />
                    <q-btn
                      flat
                      color="white"
                      icon="close"
                      class="bg-deep-orange"
                      label="取消"
                      @click="closeReplyBox(post1.id)"
                    />
                  </div>
                </q-card-section>
                <q-card-section>
                  <div class="replies">
                    <div
                      v-for="reply in hotPost.postReplyList"
                      :key="reply.id"
                      class="reply-card"
                    >
                      <q-item>
                        <q-item-section>
                          <div>{{ reply.content }}</div>
                          <div class="text-subtitle2">
                            {{ reply.replydate }}
                          </div>
                        </q-item-section>
                        <q-item-section avatar>
                          <q-avatar
                            ><img :src="reply.imgUrl" alt=""
                          /></q-avatar>
                          <div class="text-subtitle2">
                            By {{ reply.username }}
                          </div>
                        </q-item-section>
                      </q-item>
                    </div>
                  </div>
                </q-card-section>
              </q-card>
            </div>
            <div class="q-pa-lg flex flex-center">
              <q-pagination
                v-model="currentHotPage"
                :max="totalHotPage"
                input
                @update:model-value="handleHotPageChange"
              />
            </div>
          </q-tab-panel>
        </q-tab-panels>
      </template>
    </q-splitter>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { baseurl } from "src/js/global";
import { useQuasar } from "quasar";
import { get, post } from "src/js/fetch";

const $q = useQuasar();
const dialog = ref(false);
const totalPage = ref(5);
const current = ref(1);
const currentHotPage = ref(1);
const totalHotPage = ref(1);
const tab = ref("mails");
const splitterModel = ref(20);
const slide = ref("style");
const postTitle = ref("");
const postContent = ref("");

const posts = ref([]);
const hotPosts = ref([]);
const text = ref("");
const replyBoxOpen = ref({});
const searchposts = ref([]);
const replys = ref([]);

// const editorFonts = {
//   arial: "Arial",
//   arial_black: "Arial Black",
//   comic_sans: "Comic Sans MS",
//   courier_new: "Courier New",
//   impact: "Impact",
//   lucida_grande: "Lucida Grande",
//   times_new_roman: "Times New Roman",
//   verdana: "Verdana",
// };
const handlePageChange = (page) => {
  current.value = page;
  fetchAllPosts();
};
const handleHotPageChange = (page) => {
  currentHotPage.value = page;
  fetchHotPosts();
};

const toolbarOptions = [
  [
    {
      label: $q.lang.editor.align,
      icon: $q.iconSet.editor.align,
      fixedLabel: true,
      list: "only-icons",
      options: ["left", "center", "right", "justify"],
    },
  ],
  [
    {
      label: $q.lang.editor.align,
      icon: $q.iconSet.editor.align,
      fixedLabel: true,
      options: ["left", "center", "right", "justify"],
    },
  ],
  ["bold", "italic", "strike", "underline", "subscript", "superscript"],
  ["token", "hr", "link", "custom_btn"],
  ["print", "fullscreen"],
  [
    {
      label: $q.lang.editor.formatting,
      icon: $q.iconSet.editor.formatting,
      list: "no-icons",
      options: ["p", "h1", "h2", "h3", "h4", "h5", "h6", "code"],
    },
  ],
  [
    {
      label: $q.lang.editor.fontSize,
      icon: $q.iconSet.editor.fontSize,
      fixedLabel: true,
      fixedIcon: true,
      list: "no-icons",
      options: [
        "size-1",
        "size-2",
        "size-3",
        "size-4",
        "size-5",
        "size-6",
        "size-7",
      ],
    },
  ],
  [
    {
      label: $q.lang.editor.defaultFont,
      icon: $q.iconSet.editor.font,
      fixedIcon: true,
      list: "no-icons",
      options: [
        "default_font",
        "arial",
        "arial_black",
        "comic_sans",
        "courier_new",
        "impact",
        "lucida_grande",
        "times_new_roman",
        "verdana",
      ],
    },
  ],
  "removeFormat",
  ["quote", "unordered", "ordered", "outdent", "indent"],
  ["undo", "redo"],
  ["viewsource"],
];

onMounted(() => {
  fetchAllPosts();
});

const fetchAllPosts = () => {
  const url = `${baseurl}post/list?current=${current.value}`;
  get(url)
    .then((res) => {
      if (res.success) {
        posts.value = res.data;
        totalPage.value = res.totalPage;
      } else {
        $q.notify({ message: "请先登录", type: "warning", position: "center" });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};
const fetchHotPosts = () => {
  const url = `${baseurl}post/hot?current=${currentHotPage.value}`;
  get(url)
    .then((res) => {
      if (res.success) {
        hotPosts.value = res.data;
        totalHotPage.value = res.totalPage;
      } else {
        $q.notify({ message: "请先登录", type: "warning", position: "center" });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};

const imgError = (event) => {
  event.target.src = "https://t1.chei.com.cn/common/xh/default.jpg";
};

const openDialog = (userid) => {
  dialog.value = true;
  fetchPostDetails(userid);
};

const closeDialog = () => {
  dialog.value = false;
};

const fetchPostDetails = (userid) => {
  const urlPostSelect = `${baseurl}post/post/${userid}?current=1`;
  get(urlPostSelect)
    .then((res) => {
      if (res.success) {
        searchposts.value = res.data;
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));

  const urlReply = `${baseurl}post/reply/${userid}?current=1`;
  get(urlReply)
    .then((res) => {
      if (res.success) {
        replys.value = res.data;
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};

const toggleReplyBox = (id) => {
  replyBoxOpen.value[id] = !replyBoxOpen.value[id];
};

const closeReplyBox = (id) => {
  replyBoxOpen.value[id] = false;
};

const submitReply = (postid) => {
  if (text.value.trim() === "") {
    $q.notify({
      message: "你还没留言 重来",
      type: "warning",
      position: "center",
    });
    return;
  }
  const replyData = { postid: postid, content: text.value };
  const urlPostReply = `${baseurl}post/reply/add`;
  post(urlPostReply, replyData)
    .then((res) => {
      if (res.success) {
        $q.notify({ message: res.data, type: "positive", position: "center" });
        fetchAllPosts();
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};

const deletePost = (postid) => {
  const urlPostDelete = `${baseurl}post/post/delete?postId=${postid}`;
  post(urlPostDelete)
    .then((res) => {
      if (res.success) {
        fetchAllPosts();
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};

const submitNewPost = () => {
  const postData = { title: postTitle.value, content: postContent.value };
  const urlPostAdd = `${baseurl}post/add`;
  post(urlPostAdd, postData)
    .then((res) => {
      if (res.success) {
        $q.notify({ message: res.data, type: "positive", position: "center" });
        fetchAllPosts();
        postTitle.value = "";
        postContent.value = "";
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};

const handleReplyClick = (postid) => {
  postid.value = postid;
};

const toggleLike = (postId) => {
  const url = `${baseurl}post/like?postId=${postId}`;
  post(url)
    .then((res) => {
      if (res.success) {
        $q.notify({ message: res.data, type: "positive", position: "center" });
        fetchAllPosts();
      } else {
        $q.notify({
          message: res.errorMsg,
          type: "warning",
          position: "center",
        });
      }
    })
    .catch((error) => console.error(`Request failed: ${error}`));
};
</script>

<style scoped>
.fontya {
  font-weight: bold;
  color: #0086ff;
}

.container {
  display: flex;
  align-items: flex-start;
}

.post-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 10px;
}

.post-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

#username {
  font-weight: bold;
  font-size: 18px;
}

.my-card-post {
  margin-bottom: 30px;
  width: 100%;
}

.container2 {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.post-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.post-content {
  font-size: 16px;
}

.like-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 10px;
  font-size: 20px;
}

.like-icon {
  cursor: pointer;
  margin-right: 5px;
}

.reply-card {
  border-top: 1px solid #e0e0e0;
}

.post-card {
  border-top: 1px solid #e0e0e0;
}

.action-buttons {
  justify-content: flex-start;
}
</style>
